<template>
  <div ref="canvas" style="width: 100%; height: 210px"></div>
</template>
<script setup>
  import * as echarts from 'echarts';

  import { ref, inject, watchEffect, onMounted } from 'vue';

  const props = defineProps({
    code: String
  });

  const $http = inject('$http');
  const $eventBus = inject('$eventBus');

  const canvas = ref([]);

  let echartsInstance = null;
  const echartsOption = {
    grid: {
      left: '15px',
      right: '15px',
      bottom: '0',
      top: '35px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      formatter: function (params) {
        let result = `${params[0].name}<br />`;

        params.forEach(item => {
          let unit = item.seriesName == '涨幅' ? '%' : '元';

          result += `<p class="chart-tooltip-line"><b>${item.marker}${item.seriesName}</b> <b>${item.value} ${unit}</b></p>`;
        });

        return result;
      }
    },
    legend: {
      align: 'left',
      data: ['价格', '涨幅']
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '价格(元)',
        min: 0,
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '涨幅(%)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '价格',
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      },
      {
        name: '涨幅',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            } else {
              return 'green';
            }
          }
        }
      }
    ],
    visualMap: {
      show: false,
      // 只对第二条线进行设置
      seriesIndex: 1,
      textStyle: {
        color: '#000'
      },
      pieces: [
        { min: 0, max: 2000000, label: '涨', color: '#C1232B' },
        { min: -20000, max: 0, label: '跌', color: 'green' }
      ],
      outOfRange: {
        color: 'green'
      }
    }
  };

  watchEffect(() => getPrices());

  function getPrices() {
    $http.get(`/api/shares/${props.code}/prices`, { hideTip: true }).then(res => {
      let d = res.datas;

      echartsOption.xAxis.data = d.map(function (m) {
        return `${m.Date}`;
      });

      echartsOption.series[0].data = d.map(function (m) {
        return m.CurrentPrice.toFixed(2);
      });

      echartsOption.series[1].data = d.map(function (m) {
        return (((m.CurrentPrice - m.StartPrice) / m.StartPrice) * 100).toFixed(2);
      });

      // 使用刚指定的配置项和数据显示图表。
      echartsInstance.setOption(echartsOption);
    });
  }

  onMounted(() => {
    echartsInstance = echarts.init(canvas.value);

    // 使用刚指定的配置项和数据显示图表。
    echartsInstance.setOption(echartsOption);

    getPrices();

    $eventBus.on(`reload_${props.code}`, () => getPrices());
    $eventBus.on('windowResizeChanged', client => {
      let canvasDom = canvas.value;

      if (canvasDom) {
        canvasDom.style.width = window.innerWidth - 120 + 'px';
      }

      if (echartsInstance) {
        echartsInstance.resize();
      }
    });
  });
</script>

<style lang="less">
  .chart-tooltip-line {
    line-height: 22px;
    margin-bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
    min-width: 160px;

    >b{
      flex: 1;

      &:last-of-type{
        text-align: right;
      }
    }
  }
</style>
